const db = wx.cloud.database();    // This line is essential
Page({
 
  /**
   * Initial data of the page
   */
  data: {
    username: '', // Username
    mobile: '', // Mobile phone number
    pass1: '', // Password
    pass2: '', // Confirm password
  },
  // When the username input loses focus
  username(e) {
    this.setData({
      username: e.detail.value
    });
  },
  // When the mobile phone number input loses focus
  mobile(e) {
    this.setData({
      mobile: e.detail.value
    });
  },
  // When the password input loses focus
  pass1(e) {
    var pattern = /^[\w_]{8,16}$/; // Password regular expression
    if (!pattern.test(e.detail.value)) {
      this.setData({
        pass1: ''
      });
      wx.showToast({
        title: 'The password must be 8 - 16 characters long and consist of letters, numbers, or underscores.',
        icon: 'none',
        duration: 3000
      });
    } else {
      this.setData({
        pass1: e.detail.value
      });
    }
  },
  // When the confirm password input loses focus
  pass2(e) {
    this.setData({
      pass2: e.detail.value
    });
  },
  // When the register button is clicked
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      // The user clicked the allow authorization button
      wx.showLoading({
        title: 'Registering...',
      });
      if (this.data.username === '') {
        wx.showToast({
          title: 'Username cannot be empty.',
          icon: 'none',
          duration: 2000
        });
      } else if (this.data.mobile === '') {
        wx.showToast({
          title: 'Mobile phone number cannot be empty.',
          icon: 'none',
          duration: 2000
        });
      } else if (!(/^1[3456789]\d{9}$/.test(this.data.mobile))) {
        wx.showToast({
          title: 'The mobile phone number format is incorrect. Please re - enter!',
          icon: 'none',
          duration: 2000
        });
      } else if (this.data.pass1 === '') {
        wx.showToast({
          title: 'Password cannot be empty.',
          icon: 'none',
          duration: 2000
        });
      } else if (this.data.pass2 === '') {
        wx.showToast({
          title: 'Please enter the password again.',
          icon: 'none',
          duration: 2000
        });
      } else if (this.data.pass1 !== this.data.pass2) {
        wx.showToast({
          title: 'The two passwords do not match. Please re - enter!',
          icon: 'none',
          duration: 2000
        });
      } else {
        var that = this;
        // Before registering this account, we first need to check if this user already exists in the collection table.
        db.collection('login_info').where({ // Query interface
            username: that.data.username // Pass the input username as a parameter
          })
          .get({
            success: function(res) {
              if (res.data.length === 0) { // Check if the username has been registered. If it's empty, it means it hasn't been registered.
                db.collection('login_info').where({ // I set it so that both the username and mobile phone number can be used for login. So the same mobile phone number and username can only count as one account. We also need to verify if the mobile phone number has been registered.
                    mobile: that.data.mobile
                  })
                  .get({
                    success: function(res) {
                      if (res.data.length === 0) { // Check if the mobile phone number has been registered. If it's empty, it means it hasn't been registered.
                        // Get the current time and write it to the database to know when this account was created.
                        var myDate = new Date();
                        var y = myDate.getFullYear();
                        var m = myDate.getMonth() + 1;
                        var d = myDate.getDate();
                        var h = myDate.getHours();
                        var ms = myDate.getMinutes();
                        var s = myDate.getSeconds();
                        var time = y + '-' + m + '-' + d + ' ' + h + ':' + ms + ':' + s;
                        db.collection('login_info').add({ // After verification, use the add interface.
                          data: {
                            username: that.data.username, // Username
                            mobile: that.data.mobile, // Mobile phone number
                            pass1: that.data.pass1, // Password
                            time: time // Creation time
                          },
                          success: function(res) {
                            if (res.errMsg === 'collection.add:ok') { // If the interface call is successful, it means the registration is successful.
                              // You can add the logic after successful registration here, such as logging in directly or jumping to the login page.
                              wx.hideLoading();
                              wx.showToast({
                                title: 'Registration successful',
                                icon: 'none'
                              });
                            }
                          }
                        });
                      } else {
                        wx.showToast({
                          title: 'This mobile phone number has been registered by someone else. Try another one!',
                          icon: 'none',
                          duration: 2000
                        });
                      }
                    }
                  });
              } else {
                wx.showToast({
                  title: 'This username has been registered by someone else. Try another one!',
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          });
      }
    } else {
      // The user clicked the deny button
      wx.showModal({
        title: 'Warning',
        content: 'You clicked to deny authorization and will not be able to register an account. Please authorize before registering!!!',
        showCancel: false,
        confirmText: 'Return to authorization',
        success: function(res) {}
      });
    }
  },
  /**
   * Lifecycle function - Listen for page loading
   */
  onLoad: function(options) {
    
  },
 
  /**
   * Lifecycle function - Listen for the initial rendering completion of the page
   */
  onReady: function() {
 
  },
 
  /**
   * Lifecycle function - Listen for page display
   */
  onShow: function() {
 
  },
 
  /**
   * Lifecycle function - Listen for page hiding
   */
  onHide: function() {
 
  },
 
  /**
   * Lifecycle function - Listen for page unloading
   */
  onUnload: function() {
 
  },
 
  /**
   * Page-related event handling function - Listen for user pull-down actions
   */
  onPullDownRefresh: function() {
 
  },
 
  /**
   * Event handling function for reaching the bottom of the page when scrolling up
   */
  onReachBottom: function() {
 
  },
 
  /**
   * When the user clicks the share button in the upper right corner
   */
  onShareAppMessage: function() {
 
  }
});